//
//  CourseVideoViewController.m
//  xpkc
//
//  Created by TopSageOSX on 14-8-25.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "CourseVideoViewController.h"
#import "YLAppDelegate.h"

#define oritentationFlag 1

@interface CourseVideoViewController (){
    
    int list[128];//用于标记开关,内容存数组大小
    int openSection;//默认展开的
    NSString *lastStudy;//最后学习的内容
    
    VideoListModel * _videoModel;
    
    
    
    BOOL downFlag;
    /**
     *  信息字典
     */
    NSDictionary *lectureDic;
    
    NSMutableArray *listArray;//显示列表
    NSMutableArray *tempArray;//存储全部的信息的列表
    
    NSMutableArray *downloadArray;//下载数组
    
    NSMutableArray *hadArray;//已下载或队列中列表
    NSMutableArray *ingArray;//下载中列表
    NSMutableArray *downArray;//已完成列表
    
    NSMutableArray *askArray;
    
    NSTimer *mainTimer;
    
    NSTimeInterval _ltime;
    
    BOOL _oritentatFlag;
    
    
    BOOL _fullScreen;
    
    
    // NSDictionary * _getPlayUrls;
    
    
    //记录已经播放时间（切换画质用）
    NSInteger hadPlayTime;
}

@end

@implementation CourseVideoViewController{
    /**
     *  视频详细的界面
     */
    CourseVideoView *courseVideoView;
    
    DWCustomPlayerView *playerView;
    DWMoviePlayerController *player;
    //    DWMoviePlayerController *drmPlayer;
    //    DWMoviePlayerController *openPlayer;
    
    //    DWMoviePlayerController * myPlayer;
    
    DWMoviePlayerController * _openPlayer;
}
#pragma mark - view
- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IsIOS7) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    self.view.backgroundColor = [UIColor whiteColor];
    //创建播放器
    //针对加密与否创建两类播放器
    //mp4
    
    //    openPlayer = [[DWMoviePlayerController alloc]initWithUserId:DWACCOUNT_USERID_FREE key:DWACCOUNT_APIKEY_FREE];
    //    openPlayer.drmServerPort = ((YLAppDelegate *)[[UIApplication sharedApplication]delegate]).drmServer.listenPort;
    //    openPlayer.controlStyle = MPMovieControlStyleNone;
    //pcm
    //    drmPlayer = [[DWMoviePlayerController alloc]initWithUserId:DWACCOUNT_USERID key:DWACCOUNT_APIKEY];
    //    drmPlayer.drmServerPort = ((YLAppDelegate *)[[UIApplication sharedApplication]delegate]).drmServer.listenPort;
    //    logdebug(@"drmSeerverPort: %d", drmPlayer.drmServerPort);
    //    drmPlayer.controlStyle = MPMovieControlStyleNone;
    //    if (0) {//默认用加密的
    //        logdebug(@"非加密");
    //        player = openPlayer;
    //    }else{
    //        logdebug(@"加密");
    //        player = drmPlayer;
    //    }
    //    logdebug(@"player:%@",player);
    
    //    player = [[DWMoviePlayerController alloc] initWithUserId:DWACCOUNT_USERID key:DWACCOUNT_APIKEY];
    //
    //    player.drmServerPort =((YLAppDelegate *)[[UIApplication sharedApplication]delegate]).drmServer.listenPort;
    //
    //    player.controlStyle = MPMovieControlStyleNone;
    
    
    //    drmPlayer = player;
    //设置Drm端口
    //获取信息
    listArray = [NSMutableArray array];
    tempArray = [NSMutableArray array];
    hadArray = [NSMutableArray array];
    ingArray = [NSMutableArray array];
    downArray= [NSMutableArray array];
    downloadArray = [NSMutableArray array];
    askArray = [NSMutableArray array];
    downFlag = NO;
    
    mainTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(mainTimerFunc:) userInfo:nil repeats:YES];
    [mainTimer fire];
    [self creatInfoView];
    [self getClassInfo];
}

- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
    [[UIDevice currentDevice]setValue:[NSNumber numberWithInteger:UIInterfaceOrientationMaskAllButUpsideDown] forKey:@"orientation"];
    
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(oritentationchange:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
    [[UIDevice currentDevice]setValue:[NSNumber numberWithInteger:UIInterfaceOrientationMaskPortrait] forKey:@"orientation"];
    
    
    
}
///**
// *  返回按钮
// */
//-(void)backToLastView{
//    //记录当前的播放时间
//    if (player.currentPlaybackTime == player.duration) {
//        //
//        [LocalTime saveTheTime:0 withVideoID:videoID];
//    }else{
//        [LocalTime saveTheTime:player.currentPlaybackTime withVideoID:videoID];
//    }
//    player.fullscreen = NO;
//    [mainTimer invalidate];
//    mainTimer = nil;
//    [idTimer invalidate];
//    idTimer = nil;
//    //全部清理掉
//    menuview = nil;
//    [self.player cancelRequestPlayInfo];
//    self.player.contentURL = nil;
//
//    [self.player stop];
//    self.player.initialPlaybackTime = -1;
//    [self.player.view removeFromSuperview];
//    self.player = nil;
//    self.overlayView = nil;
//    self.videoBackgroundView = nil;
//    //注销通知
//    [[NSNotificationCenter defaultCenter]removeObserver:self];
//    //退出
//    if (self.tem == 2) {
//        self.playerReturn(self.index.section *1000+self.index.row);
//    }else{
//        self.playerReturn(_nowVideo);
//    }
//
//    if (IsIOS8) {
//        [[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationPortrait];
//    }else{
//        [[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationPortrait];
//    }
//    [self dismissViewControllerAnimated:YES completion:nil];
//}

// 播放下一个
-(void)nextVideo{
    
    NSLog(@"%ld",self.section);
    NSDictionary *dict = [listArray objectAtIndex:self.section];
    NSArray *array = [dict objectForKey:@"array"];
    NSInteger index = [array indexOfObject:_videoModel];
    NSLog(@"%ld",index);
    if (index >= array.count) {
        
        //最后了，返回
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"已到最后一讲" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
        return;
    }
    
    VideoListModel * listModel = array[index + 1];
    [player pause];
    [player stop];
    player.videoId = nil;
    _oritentatFlag = NO;
    [player cancelRequestPlayInfo];
    
    
    [_openPlayer pause];
    [_openPlayer stop];
    _openPlayer.videoId = nil;
    [_openPlayer cancelRequestPlayInfo];
    
    [self coursePlayWithModel:listModel];
}

// 播放前一个
-(void)passVideo{
    
    NSLog(@"播放前一个");
    NSLog(@"%ld",self.section);
    NSDictionary *dict = [listArray objectAtIndex:self.section];
    NSArray *array = [dict objectForKey:@"array"];
    NSInteger index = [array indexOfObject:_videoModel];
    NSLog(@"%ld",index);
    if (index <= 0) {
        
        //最后了，返回
        //        [self backToCourseVC];
        
        
        
        //        if (([UIDevice currentDevice].orientation == 3) || ([UIDevice currentDevice].orientation == 4)) {
        //            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"已经是第一讲" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil];
        //            alert.transform = CGAffineTransformMakeRotation(M_PI_4);
        //            [alert show];
        ////            alert.transform = CGAffineTransformRotate(alert.transform, M_PI_2);
        //        }
        
        
        
        return;
    }
    
    VideoListModel * listModel = array[index - 1];
    
    //    _videoModel = listModel;
    
    //    if ([hadArray containsObject:listModel]) {
    //
    //        [self courseOffLine:listModel.spark];
    //    }else{
    [player pause];
    [player stop];
    player.videoId = nil;
    _oritentatFlag = NO;
    [player cancelRequestPlayInfo];
    [self coursePlayWithModel:listModel];
    
    
    
}

/**
 *  创建视图
 *
 */
-(void)creatInfoView{
    courseVideoView = [[CourseVideoView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    courseVideoView.delegate = self;
    courseVideoView.listTab.delegate = self;
    courseVideoView.listTab.dataSource = self;
    courseVideoView.questTab.delegate = self;
    courseVideoView.questTab.dataSource = self;
    courseVideoView.menuFull.halfDelegate = self;
    
    
    
    
    [courseVideoView.askBtn addTarget:self action:@selector(askQuset:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:courseVideoView];
    
    // 返回上一界面
    [courseVideoView.menuFull.backBtn addTarget:self action:@selector(halfScreenPlayer) forControlEvents:UIControlEventTouchUpInside];
    
    // 半屏
    [courseVideoView.menuFull.halfBtn addTarget:self action:@selector(halfScreenPlayer) forControlEvents:UIControlEventTouchUpInside];
    
    // 全屏
    [courseVideoView.menuMini.fullBtn addTarget:self action:@selector(fullScreenPlayer) forControlEvents:UIControlEventTouchUpInside];
    
    // 画质
    [courseVideoView.menuFull.qualityBtn addTarget:self action:@selector(menuQualityClick:) forControlEvents:UIControlEventTouchUpInside];
    
    // 播放前一个
    [courseVideoView.menuFull.nextBtn addTarget:self action:@selector(nextVideo) forControlEvents:UIControlEventTouchUpInside];
    
    // 播放后一个
    [courseVideoView.menuFull.previBtn addTarget:self action:@selector(passVideo) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)playerSetQuality:(NSInteger)quality{
    
    //    NSLog(@"%ld--%@",quality,self.playUrls);
    //    NSLog(@"设置画质");
    NSArray *array = [self.playUrls objectForKey:@"qualities"];
    NSDictionary *urlDic = [array objectAtIndex:quality];
    
    if ([self.currentPlayUrl objectForKey:@"quality"] != [urlDic objectForKey:@"quality"]) {
        
        self.currentPlayUrl = urlDic;
        
    }else{
        
        return;
    }
    
    
    //记录当前播放时间
    hadPlayTime = player.currentPlaybackTime;
    
    if ([_videoModel.drm isEqualToString:@"0"]) {
        hadPlayTime = _openPlayer.currentPlaybackTime;
    }
    
    courseVideoView.menuFull.qualitiesNoteLabel.hidden = NO;
    //重置播放器
    [self resetPlayer];
    
}

/**
 *  重置播放器
 */
- (void)resetPlayer
{
    NSLog(@"%@",self.playUrls);
    
    NSLog(@"%@",self.currentPlayUrl);
    [player stop];
    
    player.contentURL = [NSURL URLWithString:[self.currentPlayUrl objectForKey:@"playurl"]];
    //跳转已经播放的时间
    player.initialPlaybackTime = hadPlayTime;
    player.currentPlaybackTime = hadPlayTime;
    //    courseVideoView.menuFull.noteLabel.hidden = NO;
    //    menuview.noteLabel.text = @"切换中...";
    courseVideoView.menuFull.playBtn.selected = YES;
    [player prepareToPlay];
    [player play];
    
    //    sleep(2);
    
    courseVideoView.menuFull.qualitiesNoteLabel.hidden = YES;
    
}


// 出现选择画质
- (void)menuQualityClick:(UIButton *)btn{
    logdebug(@"画质");
    if (btn.selected) {
        [courseVideoView.menuFull closeQuality];
    }else{
        [courseVideoView.menuFull openQuality];
    }
}
#pragma mark -- 全屏

- (void)fullScreenPlayer{
    courseVideoView.menuMini.hidden = YES;
    courseVideoView.menuFull.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        courseVideoView.playerView.transform = CGAffineTransformMakeRotation(M_PI_2* 5);
        courseVideoView.playerView.transform = CGAffineTransformTranslate(courseVideoView.playerView.transform, SCREEN_HEIGHT/2-SCREEN_WIDTH*SCREEN_WIDTH/SCREEN_HEIGHT/2, 0);
        courseVideoView.playerView.transform = CGAffineTransformScale(courseVideoView.playerView.transform, SCREEN_HEIGHT/SCREEN_WIDTH, SCREEN_HEIGHT/SCREEN_WIDTH);
        
        courseVideoView.menuFull.progressView.transform = CGAffineTransformMakeTranslation(-(SCREEN_HEIGHT-SCREEN_WIDTH)/2, 0);
        courseVideoView.menuFull.progressView.transform = CGAffineTransformScale(courseVideoView.menuFull.progressView.transform, SCREEN_WIDTH/SCREEN_HEIGHT, SCREEN_WIDTH/SCREEN_HEIGHT);
        
        _fullScreen = YES;
        
    }];
    
    
    
    [[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:YES];
}

#pragma mark -- 半屏

- (void)halfScreenPlayer{
    courseVideoView.menuMini.hidden = NO;
    courseVideoView.menuFull.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        CGAffineTransform transform = CGAffineTransformMakeRotation(0);
        transform = CGAffineTransformScale(transform, 1, 1);
        transform = CGAffineTransformTranslate(transform, 0, 0);
        courseVideoView.playerView.transform = transform;
        
        CGRect rect = courseVideoView.playerView.frame;
        
        rect.origin.x += 0.01;
        
        player.view.frame = rect;
        
        _fullScreen = NO;
        
    }];
    [[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationPortrait animated:YES];
}



#pragma mark - view delegate

- (void)backToCourseVC{
    [player stop];
    [player cancelRequestPlayInfo];
    //    [drmPlayer stop];
    //    [drmPlayer cancelRequestPlayInfo];
    //    drmPlayer = nil;
    //    [openPlayer stop];
    //    [openPlayer cancelRequestPlayInfo];
    //    openPlayer = nil;
    [self.navigationController popViewControllerAnimated:YES];
    [mainTimer invalidate];
    mainTimer = nil;
}
- (void)playerPause{
    [player pause];
    courseVideoView.isPlay = NO;
}
- (void)playerPlay{
    [player play];
    courseVideoView.isPlay = YES;
}
- (void)playerSetRate:(CGFloat)rate{
    player.currentPlaybackRate = rate;//设置播放速率
}
- (void)playerChangeToSection:(NSInteger)section andRow:(NSInteger)row{
    NSDictionary *dict = [listArray objectAtIndex:section];
    NSArray *array = [dict objectForKey:@"array"];
    VideoListModel *model = [array objectAtIndex:row];
    //    static NSString * str = nil;
    //    if (str == nil) {
    //
    //        _videoModel = model;
    //    }
    
    _oritentatFlag = YES;
    [player pause];
    [player stop];
    player.videoId = nil;
    [player cancelRequestPlayInfo];
    [self coursePlayWithModel:model];
}


/**
 选择画质
 */
//- (void)playerSetQuality:(NSInteger)quality{
//    NSLog(@"选择画质%ld",quality);
//
//
//
//
//}
- (void)playerSetProgress:(CGFloat)progress{
    player.currentPlaybackTime = player.duration * progress;
    [player play];
    courseVideoView.menuFull.playBtn.selected = YES;
    courseVideoView.menuMini.playBtn.selected = YES;
}


- (void)downBtnClick:(UIButton *)btn{
    downFlag = YES;
    [courseVideoView.listTab reloadData];
    for (int i = 0; i<listArray.count; i++) {
        [courseVideoView.listTab reloadSections:[NSIndexSet indexSetWithIndex:i] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    [courseVideoView.listTab setEditing:YES animated:YES];
    
}
- (void)closeDownBtnClick:(UIButton *)btn{
    downFlag = NO;
    [courseVideoView.listTab reloadData];
    for (int i = 0; i<listArray.count; i++) {
        [courseVideoView.listTab reloadSections:[NSIndexSet indexSetWithIndex:i] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    [courseVideoView.listTab setEditing:NO animated:YES];
    [downloadArray removeAllObjects];
}
- (void)downChooseAll:(UIButton *)btn{
    if (btn.selected) {//取消全选
        btn.selected = NO;
        //删除数组
        [downloadArray removeAllObjects];
        //复原状态
        for (int i = 0; i<listArray.count; i++) {
            NSDictionary *dict = [listArray objectAtIndex:i];
            NSArray *array = [dict objectForKey:@"array"];
            for (int j = 0; j<array.count; j++) {
                [courseVideoView.listTab deselectRowAtIndexPath:[NSIndexPath indexPathForItem:j inSection:i] animated:YES];
            }
        }
    }else{
        btn.selected = YES;
        //添加数组
        [downloadArray removeAllObjects];
        for (int i = 0; i<listArray.count; i++) {
            NSDictionary *dict = [listArray objectAtIndex:i];
            NSArray *array = [dict objectForKey:@"array"];
            for (int j = 0; j<array.count; j++) {
                VideoListModel *model = [array objectAtIndex:j];
                if (model.videoId) {
                    //
                }
            }
        }
        //选中状态
        for (int i = 0; i<listArray.count; i++) {
            NSDictionary *dict = [listArray objectAtIndex:i];
            NSArray *array = [dict objectForKey:@"array"];
            for (int j = 0; j<array.count; j++) {
                [courseVideoView.listTab selectRowAtIndexPath:[NSIndexPath indexPathForItem:j inSection:i]animated:YES scrollPosition:UITableViewScrollPositionNone];
            }
        }
    }
}
- (void)downStartDownload:(UIButton *)btn{
    //遍历数组添加到下载
    for (int i = 0; i<downloadArray.count; i++) {
        VideoListModel *model = [downloadArray objectAtIndex:i];
        NSString *drm = [model.drm copy];
        NSString *videoId = [model.videoId copy];
        NSString *lecture_chapter = [model.chapter copy];
        NSString *lecture_section = [model.section copy];
        NSString *spark = [model.spark copy];
        NSString *teacher = [model.teacher copy];
        NSString *lecture = [model.lecture copy];
        NSString *duration = [model.duration copy];
        NSString *lectureNum = [NSString stringWithFormat:@"%lu",(unsigned long)listArray.count];
        NSString *usermid = [[UserMessage sharedUserMessage].userMid copy];
        NSDictionary *downDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                 drm,@"drm",
                                 spark,@"spark",
                                 videoId,@"videoId",
                                 lecture_chapter,@"chapter",
                                 lecture_section,@"section",
                                 teacher,@"teacher",
                                 duration,@"duration",
                                 lecture,@"lecture",
                                 lectureNum,@"lectureNum",
                                 usermid,@"usermid",
                                 nil];
        [[NSNotificationCenter defaultCenter]postNotificationName:START_DOWNLOAD_NOTIFICATION object:nil userInfo:downDic];
    }
    if (downloadArray.count==0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"您未选择要下载的课程" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
    }else{
        //提示
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"已成功添加到下载列表" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        //关闭视图
    }
}



#pragma mark - orientation
- (BOOL)shouldAutorotate{
    return YES;
}
- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskAll;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationPortrait|UIInterfaceOrientationLandscapeLeft|UIInterfaceOrientationLandscapeRight;
}
- (void)oritentationchange:(NSNotification *)noti{
    logdebug(@"方向%ld",(long)[UIDevice currentDevice].orientation);
    NSInteger or;
    if ([UIDevice currentDevice].orientation == 2) {
        or = 1;
    }else{
        or = [UIDevice currentDevice].orientation;
    }
    if (or<3) {
        [UIView animateWithDuration:0.3 animations:^{
            CGAffineTransform transform = CGAffineTransformMakeRotation(0);
            transform = CGAffineTransformScale(transform, 1, 1);
            transform = CGAffineTransformTranslate(transform, 0, 0);
            courseVideoView.playerView.transform = transform;
            courseVideoView.menuMini.hidden = NO;
            courseVideoView.menuFull.hidden = YES;
            
            if (![downArray containsObject:_videoModel]) {
                
                CGRect rect = courseVideoView.playerView.frame;
                
                rect.origin.x += 0.0001;
                
                player.view.frame = rect;
                
                
                _fullScreen = NO;
                //                [courseVideoView.listTab reloadData];
            }
            
        }];
    }
    
    if ([UIDevice currentDevice].orientation == 3) {
        [UIView animateWithDuration:0.3 animations:^{
            courseVideoView.playerView.transform = CGAffineTransformMakeRotation(M_PI_2);
            courseVideoView.playerView.transform = CGAffineTransformTranslate(courseVideoView.playerView.transform, SCREEN_HEIGHT/2-SCREEN_WIDTH*SCREEN_WIDTH/SCREEN_HEIGHT/2, 0);
            courseVideoView.playerView.transform = CGAffineTransformScale(courseVideoView.playerView.transform, SCREEN_HEIGHT/SCREEN_WIDTH, SCREEN_HEIGHT/SCREEN_WIDTH);
            courseVideoView.menuMini.hidden = YES;
            courseVideoView.menuFull.hidden = NO;
            
            //            CGRect rect = courseVideoView.playerView.frame;
            //
            //            rect.origin.x -= 0.01;
            //
            //            player.view.frame = rect;
            
            //            if (![downArray containsObject:_videoModel]) {
            //
            //                CGRect rect = courseVideoView.playerView.frame;
            //
            //                rect.origin.x += SCREEN_HEIGHT * 0.25 + 20;
            //
            //                player.view.frame = rect;
            //
            //                [courseVideoView.listTab reloadData];
            //            }
            
            NSLog(@"左屏");
        }];
    }
    if ([UIDevice currentDevice].orientation == 4) {
        [UIView animateWithDuration:0.3 animations:^{
            courseVideoView.playerView.transform = CGAffineTransformMakeRotation(-M_PI_2);
            courseVideoView.playerView.transform = CGAffineTransformTranslate(courseVideoView.playerView.transform, -(SCREEN_HEIGHT/2-SCREEN_WIDTH*SCREEN_WIDTH/SCREEN_HEIGHT/2), 0);
            courseVideoView.playerView.transform = CGAffineTransformScale(courseVideoView.playerView.transform, SCREEN_HEIGHT/SCREEN_WIDTH, SCREEN_HEIGHT/SCREEN_WIDTH);
            courseVideoView.menuMini.hidden = YES;
            courseVideoView.menuFull.hidden = NO;
            
            
            //            CGRect rect = courseVideoView.playerView.frame;
            //
            //            rect.origin.x -= SCREEN_HEIGHT * 0.25 + 20;
            //
            //            player.view.frame = rect;
            
            
            
            
            //            if (![downArray containsObject:_videoModel]) {
            //
            //                CGRect rect = courseVideoView.playerView.frame;
            //
            //                rect.origin.x += SCREEN_HEIGHT * 0.25 + 20;
            //
            //                player.view.frame = rect;
            //
            //                [courseVideoView.listTab reloadData];
            //            }
            
            NSLog(@"右屏");
        }];
    }
    [[UIApplication sharedApplication]setStatusBarOrientation:or animated:YES];
}

#pragma mark - tableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView.tag == 1) {
        return listArray.count;
    }else{
        return askArray.count;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 1) {
        if (downFlag) {
            NSDictionary *dict = [listArray objectAtIndex:section];
            NSArray *array = [dict objectForKey:@"array"];
            return array.count;
        }else{
            if (list[section] == 0) {
                return 0;
            }else{
                NSDictionary *dict = [listArray objectAtIndex:section];
                NSArray *array = [dict objectForKey:@"array"];
                return array.count;
            }
        }
    }else{
        NSDictionary *dic = [askArray objectAtIndex:section];
        NSArray *array = [dic valueForKey:@"ReplyList"];
        return array.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView.tag == 1) {
        return 40;
    }else{
        CourseListAskCell *cell = [[CourseListAskCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"quest"];
        NSDictionary *dic = [askArray objectAtIndex:section];
        NSString *content = [dic objectForKey:@"myaskcontent"];
        CGFloat height = [content heightForString:content withWidth:cell.contentLabel.width andFont:cell.contentLabel.font];
        return height + 0.08*SCREEN_WIDTH;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView.tag == 1) {
        CourseListCellHeaderView *header = [[CourseListCellHeaderView alloc]init];
        NSDictionary *dict = [listArray objectAtIndex:section];
        header.chapter.text = [dict objectForKey:@"chapter"];
        header.headBtn.tag = section;
        if (list[section]==0) {
            [header close:YES];
        }else{
            [header close:NO];
        }
        [header.headBtn addTarget:self action:@selector(openOrCloseSection:) forControlEvents:UIControlEventTouchUpInside];
        if (downFlag) {
            [header move:1];
            header.userInteractionEnabled = NO;
            [header close:NO];
        }else{
            [header move:2];
            header.userInteractionEnabled = YES;
        }
        logdebug(@"头部视图");
        return header;
    }else{
        CourseListAskCell *cell = [[CourseListAskCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"quest"];
        cell.questionStyle = QuestionStyleAsk;
        NSDictionary *dic = [askArray objectAtIndex:section];
        NSString *content = [dic objectForKey:@"myaskcontent"];
        CGFloat height = [content heightForString:content withWidth:cell.contentLabel.width andFont:cell.contentLabel.font];
        CGFloat bgheight = height + 0.04*SCREEN_WIDTH;
        cell.contentLabel.text = content;
        cell.contentLabel.height = height;
        logdebug(@"%f",height);
        cell.contentBG.height = bgheight;
        NSURL *imgurl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",URL2,[dic valueForKey:@"myavtar"]]];
        logdebug(@"%@",imgurl.absoluteString);
        [cell.headImgView setImageWithURL:imgurl placeholderImage:[UIImage imageNamed:@"pro"]];
        cell.userName.text = [dic valueForKey:@"myname"];
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 1) {
        return 40;
    }else{
        NSDictionary *Dic = [askArray objectAtIndex:indexPath.section];
        NSArray *replys = [Dic valueForKey:@"ReplyList"];
        NSDictionary *reply = [replys objectAtIndex:indexPath.row];
        NSString *content = [reply objectForKey:@"reply"];
        CourseListAskCell *cell = [[CourseListAskCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"quest"];
        CGFloat height = [content heightForString:content withWidth:cell.contentLabel.width andFont:cell.contentLabel.font];
        return height + 0.12*SCREEN_WIDTH + 30;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 1) {
        CourseListHalfCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list"];
        if (cell == nil) {
            cell = [[CourseListHalfCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"list"];
        }
        NSDictionary *dict = [listArray objectAtIndex:indexPath.section];
        NSArray *array = [dict objectForKey:@"array"];
        VideoListModel *model = [array objectAtIndex:indexPath.row];
        
        [cell configCellWithVideolistModel:model];
        
        BOOL had = false;
        if ([ingArray containsObject:model]) {
            cell.downState.text = @"下载中";
            cell.downState.textColor = OrangeColor;
            had = YES;
        }
        if ([downArray containsObject:model]) {
            cell.downState.text = @"已下载";
            cell.downState.textColor = GreenColor;
            had = YES;
        }
        if (!had) {
            cell.downState.text = @"未下载";
            cell.downState.textColor = [UIColor lightGrayColor];
        }
        cell.lectureChapter.text = model.section;
        cell.teacher.text = model.teacher;
        cell.isNew = NO;
        cell.duration.text = [NSString stringWithFormat:@"%@分",model.duration];
        return cell;
    }else{
        CourseListAskCell *cell = [tableView dequeueReusableCellWithIdentifier:@"quest"];
        if (cell == nil) {
            cell = [[CourseListAskCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"quest"];
        }
        
        NSDictionary *Dic = [askArray objectAtIndex:indexPath.section];
        NSArray *replys = [Dic valueForKey:@"ReplyList"];
        NSDictionary *reply = [replys objectAtIndex:indexPath.row];
        cell.contentLabel.text = [reply valueForKey:@"reply"];
        NSURL *imgurl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",URL2,[reply valueForKey:@"uavtar"]]];
        [cell.headImgView setImageWithURL:imgurl];
        cell.userName.text = [reply valueForKey:@"username"];
        cell.questionStyle = QuestionStyleReply;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    self.section = indexPath.section;
    NSDictionary *dict = [listArray objectAtIndex:indexPath.section];
    NSArray *array = [dict objectForKey:@"array"];
    VideoListModel *model = [array objectAtIndex:indexPath.row];
    
    _videoModel = model;
    
    
    if (tableView.tag == 1) {
        //        NSDictionary *dict = [listArray objectAtIndex:indexPath.section];
        //        NSArray *array = [dict objectForKey:@"array"];
        //        VideoListModel *model = [array objectAtIndex:indexPath.row];
        if (!downFlag) {
            [player pause];
            [player stop];
            player.videoId = nil;
            _oritentatFlag = NO;
            [player cancelRequestPlayInfo];
            [self coursePlayWithModel:model];
        }else{
            //添加到下载数组中
            [downloadArray addObject:model];
        }
    }
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 1) {
        NSDictionary *dict = [listArray objectAtIndex:indexPath.section];
        NSArray *array = [dict objectForKey:@"array"];
        VideoListModel *model = [array objectAtIndex:indexPath.row];
        if (downFlag) {
            [downloadArray removeObject:model];
        }
    }
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (downFlag) {
        if ([hadArray containsObject:indexPath]) {//判断是否已经下载
            return UITableViewCellEditingStyleNone;
        }else{
            return UITableViewCellEditingStyleInsert|UITableViewCellEditingStyleDelete;
        }
    }else{
        return UITableViewCellEditingStyleNone;
    }
}

#pragma mark - func
/**
 *  获取视频课程的详细信息
 *
 */
-(void)getClassInfo{
    
    NSString *module = @"myCourse";
    NSString *interface = @"lecturelist";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *paramters = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"time",[UserMessage sharedUserMessage].userMid,@"mid",self.classId,@"course_id", nil];
    
    NSLog(@"99999----%@",urlString);
    NSLog(@"-----%@",paramters);
    
    
    //请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:paramters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //成功
//        lectureDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //之后创建视图
        logdebug(@"%@",lectureDic);
        
        lectureDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];

        
        if ([[lectureDic valueForKey:@"succ"] integerValue]) {
            logdebug(@"成功");
        }
        
        
        if (lectureDic.count == 0) {
            return ;
        }
        
        NSArray *videolist = [lectureDic valueForKey:@"LectureList"];
        NSString *courseName = [lectureDic valueForKey:@"className"];//课程名称
        //        NSString *teacher = [lectureDic valueForKey:@"teacher"];//课程讲师
        lastStudy = [NSString stringWithFormat:@"%@",[lectureDic valueForKey:@"lastStudy"]];//[[lectureDic valueForKey:@"lastStudy"] stringValue];//最后学习
        logdebug(@"最后学习%@",lastStudy);

        
        int k = 0;
        
        for (NSDictionary *videoDic in videolist) {
            VideoListModel *videoModel = [[VideoListModel alloc]init];
            videoModel.duration = [videoDic objectForKey:@"duration"];
            videoModel.videoId = [NSString stringWithFormat:@"%@",[videoDic objectForKey:@"id"]]; //[[videoDic objectForKey:@"id"] stringValue];
            videoModel.chapter = [videoDic objectForKey:@"lecture_chapter"];
            videoModel.section = [videoDic objectForKey:@"lecture_section"];
            videoModel.spark = [NSString stringWithFormat:@"%@",[videoDic objectForKey:@"spark"]];
            videoModel.drm = [NSString stringWithFormat:@"%@",[videoDic objectForKey:@"drm"]];//[[videoDic objectForKey:@"drm"] stringValue];
            videoModel.teacher = [videoDic objectForKey:@"teacher"]!=[NSNull null]?[videoDic objectForKey:@"teacher"]:@"";
            videoModel.lecture = courseName;
            videoModel.hadlocal = NO;
            //            logdebug(@"%@\n%@",videoModel.section,videoModel.chapter);
            videoModel.title = videoModel.section;
            BOOL hadmo = NO;
            NSMutableDictionary *dictinary;
            for (int i = 0; i<listArray.count; i++) {
                dictinary = [NSMutableDictionary dictionaryWithDictionary:[listArray objectAtIndex:i]];
                NSMutableArray *marray = [NSMutableArray arrayWithArray:[dictinary objectForKey:@"array"]];
                if ([[dictinary objectForKey:@"chapter"]isEqualToString:videoModel.chapter]) {
                    //
                    hadmo = YES;
                    logdebug(@"已有分组%@",videoModel.chapter);
                }
                if (hadmo) {
                    [marray addObject:videoModel];
                    [dictinary setObject:marray forKey:@"array"];
                    [listArray replaceObjectAtIndex:i withObject:dictinary];
                    if ([lastStudy isEqualToString:videoModel.videoId]) {
                        
                        
                        self.section = i;
                        openSection = i;
                        list[i] = marray.count;
                        logdebug(@"上次学习的分组：%d",i);
                        [self playLastStudyWithModel:videoModel];
                    }
                    i = listArray.count+1;//用于跳出的玩意
                    
                }
            }
            if (!hadmo) {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:videoModel];
                dictinary = [NSMutableDictionary dictionaryWithObjectsAndKeys:videoModel.chapter,@"chapter",array,@"array", nil];
                [listArray addObject:dictinary];
                
                if ([lastStudy isEqualToString:videoModel.videoId]) {
                    
                    //                    self.section = k;
                    
                    openSection = listArray.count-1;
                    list[listArray.count - 1] = array.count;
                    
                    [self playLastStudyWithModel:videoModel];
                }
            }
            
            
            k ++;
        }
        //保存暂存数组，用于展开收放等的数据
        tempArray = [NSMutableArray arrayWithArray:listArray];
        if (listArray.count==0) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"课程制作中..." delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        courseVideoView.menuFull.chapters = listArray;
        [self checkHadDown];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //失败
        logdebug(@"%@",error.localizedDescription);
    }];
}
- (void)getQuestionInfoWithLecture:(NSString *)lectureid{
    NSString *timeString = [NSString stringWithFormat:@"%@", [GetTime getTime]];
    NSString *string = [NSString stringWithFormat:@"/myCourse/mylectureasks/key/0b6f2f666ddfd0e56e4d566f12a0f353/time/%@", timeString];
    NSString *MD5string = [string md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/index.php/myCourse/mylectureasks/hash/%@/appid/1",URL2,MD5string];
    
    NSDictionary *paramters = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"time",[UserMessage sharedUserMessage].userMid,@"mid",lectureid,@"lectureid", nil];
    
    
    NSLog(@"%@---%@",urlString,paramters);
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:paramters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        logdebug(@"%@",dic);
        
        if (dic.count > 0) {
            askArray = dic[@"AskMsg"];
            [courseVideoView.questTab reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //
        logdebug(@"error%@",error.localizedDescription);
    }];
    
}

/**
 *  提问此章节
 */
- (void)askQuset:(UIButton *)btn{
    
    if (btn.selected) {
        btn.selected = NO;
    }else{
        
        btn.selected = YES;
    }
    
    if (_videoModel == nil) {
        
        
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"您还没选择提问章节" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alert show];
        btn.selected = NO;
        
        return;
        
        
    }
    
    NSString *module = @"myCourse";
    NSString *interface = @"ask";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    
    // NSString *content;
    NSString * ltime = [NSString stringWithFormat:@"%f",_ltime];
    
    NSDictionary *parameter = @{@"time":timeString,@"mid":[UserMessage sharedUserMessage].userMid,@"title":_videoModel.section,@"content":courseVideoView.askFiled.text,@"ltime":ltime,@"lectureid":_videoModel.videoId};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSLog(@"%@--%@",urlString,parameter);
    NSLog(@"title==%@--videoId==%@--ltime==%@",_videoModel.section,_videoModel.videoId,ltime);
    //    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        logdebug(@"%@",dic);
        if ([dic[@"succ"] intValue] ) {
            [self performSelectorOnMainThread:@selector(askQuestionSucc) withObject:nil waitUntilDone:YES];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //
        NSLog(@"%@",error);
    }];
}

-(void)askQuestionSucc{
    
    UIAlertView * alret = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"提问已提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
    [alret show];
    courseVideoView.askFiled.text = @"";
    courseVideoView.askBtn.selected = NO;
    
    [self getQuestionInfoWithLecture:_videoModel.videoId];
}

- (void)askQuestion{
    NSString *module = @"myCourse";
    NSString *interface = @"ask";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSString *title;
    NSString *content;
    NSString *ltime;
    NSString *lectureid;
    NSDictionary *parameter = @{@"time":timeString,@"mid":[UserMessage sharedUserMessage].userMid,@"title":title,@"content":content,@"ltime":ltime,@"lectureid":lectureid};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        logdebug(@"%@",dic);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //
    }];
}

- (void)checkHadDown{
    //遍历本地查找是否存在了
    //完成字典
    NSDictionary *downingdic = [NSDictionary dictionaryWithContentsOfFile:DOWNLOADING_PATH];
    NSArray *downingArray = [downingdic objectForKey:@"videos"];
    //下载中字典
    NSDictionary *downeddic = [NSDictionary dictionaryWithContentsOfFile:DOWNLOADED_PATH];
    NSArray *downedArray = [downeddic objectForKey:@"videos"];
    
    for (int i = 0; i<listArray.count; i++) {
        NSDictionary *dict = [listArray objectAtIndex:i];
        NSArray *array = [dict objectForKey:@"array"];
        for (int j = 0; j<array.count; j++) {
            VideoListModel *model = [array objectAtIndex:j];
            //下载中
            for (NSDictionary *downingDic in downingArray) {
                NSArray *ingLectures = [downingDic valueForKey:@"array"];
                for (NSDictionary *lecturedic in ingLectures) {
                    if ([[lecturedic valueForKey:@"videoId"]isEqualToString:model.spark]) {
                        [ingArray addObject:model];
                        [hadArray addObject:[NSIndexPath indexPathForRow:j inSection:i]];
                        break;
                    }
                }
            }
            //已下载
            for (NSDictionary *downedDic in downedArray) {//章
                NSArray *downLectures = [downedDic valueForKey:@"array"];//节数组
                for (NSDictionary *lecturedic in downLectures) {
                    if ([[lecturedic valueForKey:@"videoId"]isEqualToString:model.spark]) {
                        [downArray addObject:model];
                        [hadArray addObject:[NSIndexPath indexPathForRow:j inSection:i]];
                        break;
                    }
                }
            }
        }
    }
    logdebug(@"%@",hadArray);
    [courseVideoView.listTab reloadData];
}

- (void)openOrCloseSection:(UIButton *)btn{
    if (list[btn.tag] > 0) {
        //关闭
        list[btn.tag] = 0;
        [courseVideoView.listTab reloadSections:[NSIndexSet indexSetWithIndex:btn.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
    }else{
        //打开
        NSDictionary *dic = [listArray objectAtIndex:btn.tag];
        NSArray *array = [dic valueForKey:@"array"];
        list[btn.tag] = array.count;
        openSection = btn.tag;
        [courseVideoView.listTab reloadSections:[NSIndexSet indexSetWithIndex:btn.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (void)playLastStudyWithModel:(VideoListModel *)model{
    
    // _videoModel = model;
    [self coursePlayWithModel:model];
}

- (void)setQualityAndPlay{
        logdebug(@"%@",player.originalContentURL);
    
    NSLog(@"playUrls==>%@",self.playUrls);
    courseVideoView.playUrls = self.playUrls;
    
    
    courseVideoView.menuFull.myblock(self.playUrls);
    
    
    [player prepareToPlay];
    courseVideoView.menuMini.playBtn.selected = YES;
    courseVideoView.menuFull.playBtn.selected = YES;
    [self playerPlay];
}

- (void)mainTimerFunc:(NSTimer *)timer{
    if (player.duration >0) {
        CGFloat progress = player.currentPlaybackTime/player.duration;
        courseVideoView.menuFull.progressView.value = progress;
        _ltime = player.currentPlaybackTime;
        NSString *time = [NSString stringWithFormat:@"%02d:%02d/%02d:%02d",(int)player.currentPlaybackTime/60,(int)player.currentPlaybackTime%60,(int)player.duration/60,(int)player.duration%60];
        courseVideoView.menuFull.timeLabel.text = time;
        courseVideoView.menuMini.progress.value = progress;
    }
}

#pragma mark - player

- (void)coursePlayWithModel:(VideoListModel *)model{
    //基本赋值
    _videoModel = model;
    courseVideoView.menuMini.titleLabel.text = model.title;
    courseVideoView.menuFull.titleLabel.text = model.title;
    //    [drmPlayer stop];
    //    [drmPlayer cancelRequestPlayInfo];
    //    [openPlayer stop];
    //    [openPlayer cancelRequestPlayInfo];
    
    NSLog(@"%@",model.drm);
    if ([model.drm isEqualToString:@"1"]) {
        [self courseDRM:model];
    }else{
        [self courseFREE:model];
    }
}

- (void)courseDRM:(VideoListModel *)model{
    logdebug(@"播放加密");
    // player = drmPlayer;
    if (![downArray containsObject:model]) {
        [self courseOnLine:model.spark];
        [self getQuestionInfoWithLecture:model.videoId];
    }else{
        //离线的
        [self courseOffLine:model.spark];
    }
}
- (void)courseFREE:(VideoListModel *)model{
    // player = openPlayer;
    logdebug(@"播放未加密");
    if (![downArray containsObject:model]) {
        [self courseOnLineFree:model.spark];
        //        [self getQuestionInfoWithLecture:model.videoId];
    }else{
        [self courseOffLineFree:model.spark];
    }
}

- (void)courseOnLineFree:(NSString *)spark{
    
    
    CGFloat videoPlayOffWidth = SCREEN_HEIGHT * 0.34;
    
    if (SCREEN_HEIGHT < 568) {
        
        videoPlayOffWidth = SCREEN_HEIGHT * 0.34 - 30;
    }
    
    //    NSLog(@"w=%f--h=%f",SCREEN_WIDTH,SCREEN_HEIGHT);
    
    [player.view removeFromSuperview];
    
    player = nil;
    NSLog(@"%@",_videoModel.drm);
    
    player = [[DWMoviePlayerController alloc] initWithUserId:DWACCOUNT_USERID_FREE key:DWACCOUNT_APIKEY_FREE];
    
    
    
    
    player.drmServerPort =((YLAppDelegate *)[[UIApplication sharedApplication]delegate]).drmServer.listenPort;
    
    player.controlStyle = MPMovieControlStyleNone;
    
    //    [player.view removeFromSuperview];
    //    player.view.frame = courseVideoView.playerView.frame;
    [courseVideoView.playerView addSubview:player.view];
    [courseVideoView.playerView sendSubviewToBack:player.view];
    if ((([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight)||([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft))&&!_fullScreen) {
        
        
        
        
        if ([downArray containsObject:_videoModel]) {
            
            player.view.frame = courseVideoView.playerView.frame;
            
        }else{
            
            CGRect rect = courseVideoView.playerView.frame;
            
            //4s --- 0.25 * SCREEN_HEIGHT  + 20
            rect.origin.y -= videoPlayOffWidth;
            
            player.view.frame = rect;
            
        }
        
        
        NSLog(@"x=%f--y=%f--w=%f--h=%f",player.view.frame.origin.x,player.view.frame.origin.y,player.view.frame.size.width,player.view.frame.size.height);
        NSLog(@"横屏");
        
    }else{
        
        
        
        if (_fullScreen) {
            
            CGRect rect = courseVideoView.playerView.frame;
            
            //4s --- 0.25 * SCREEN_HEIGHT  + 20
            rect.origin.y -= videoPlayOffWidth;
            
            player.view.frame = rect;
            
        }else{
            
            player.view.frame = courseVideoView.playerView.frame;
            
        }
        
    }
    
    
    
    
    
    
    player.videoId = [NSString stringWithFormat:@"%@",spark];
    player.timeoutSeconds = 20;//10s超时
    
    
    //    [player.view removeFromSuperview];
    //    player.view.frame = courseVideoView.playerView.frame;
    //    [courseVideoView.playerView addSubview:player.view];
    //    [courseVideoView.playerView sendSubviewToBack:player.view];
    
    __block CourseVideoViewController *blockSelf = self;
    player.failBlock = ^(NSError *error) {
        logdebug(@"error: %@", [error localizedDescription]);
        //TODO:跳出或重置
        //失败的话也得置NO
        //        exchangeVideo = NO;
    };
    
    NSLog(@"videoid=%@--userid=%@--key=%@",player.videoId,player.userId,player.key);
    
    //获取播放的地址
    player.getPlayUrlsBlock = ^(NSDictionary *playUrls) {
        
        logdebug(@"%@",playUrls);
        // [必须]判断 status 的状态，不为"0"说明该视频不可播放，可能正处于转码、审核等状态。
        NSNumber *status = [playUrls objectForKey:@"status"];
        //显示不可播放的原因
        
        self.playUrls = playUrls;
        
        if (status == nil || [status integerValue] != 0) {
            NSString *message = [NSString stringWithFormat:@"%@ %@:%@",
                                 @"videoid",
                                 [playUrls objectForKey:@"status"],
                                 [playUrls objectForKey:@"statusinfo"]];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:message
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        
        [blockSelf setQualityAndPlay];
    };
    
    [player startRequestPlayInfo];
}

- (void)courseOnLine:(NSString *)spark{
    
    
    NSLog(@"spark==>%@",spark);
    
    CGFloat videoPlayOffWidth = SCREEN_HEIGHT * 0.34;
    
    if (SCREEN_HEIGHT < 568) {
        
        videoPlayOffWidth = SCREEN_HEIGHT * 0.34 - 30;
    }
    
    //    NSLog(@"w=%f--h=%f",SCREEN_WIDTH,SCREEN_HEIGHT);
    
    [player.view removeFromSuperview];
    
    player = nil;
    NSLog(@"drm==>%@",_videoModel.drm);
    
    player = [[DWMoviePlayerController alloc] initWithUserId:DWACCOUNT_USERID key:DWACCOUNT_APIKEY];
    
    player.drmServerPort =((YLAppDelegate *)[[UIApplication sharedApplication]delegate]).drmServer.listenPort;
    
    player.controlStyle = MPMovieControlStyleNone;
    
    [player.view removeFromSuperview];
    //    player.view.frame = courseVideoView.playerView.frame;
    [courseVideoView.playerView addSubview:player.view];
    [courseVideoView.playerView sendSubviewToBack:player.view];
    if ((([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight)||([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft))&&!_fullScreen) {
        
        if ([downArray containsObject:_videoModel]) {
            
            player.view.frame = courseVideoView.playerView.frame;
            
        }else{
            
            CGRect rect = courseVideoView.playerView.frame;
            
            //4s --- 0.25 * SCREEN_HEIGHT  + 20
            rect.origin.y -= videoPlayOffWidth;
            
            player.view.frame = rect;
            
        }
        
        
        NSLog(@"x=%f--y=%f--w=%f--h=%f",player.view.frame.origin.x,player.view.frame.origin.y,player.view.frame.size.width,player.view.frame.size.height);
        NSLog(@"横屏");
        
    }else{
        
        
        if (_fullScreen) {
            
            CGRect rect = courseVideoView.playerView.frame;
            
            //4s --- 0.25 * SCREEN_HEIGHT  + 20
            rect.origin.y -= videoPlayOffWidth;
            
            player.view.frame = rect;
            
        }else{
            
            player.view.frame = courseVideoView.playerView.frame;
            
        }
        
    }
    
    
    
    
    
    
    player.videoId = spark;
    player.timeoutSeconds = 20;//10s超时
    
    
    //    [player.view removeFromSuperview];
    //    player.view.frame = courseVideoView.playerView.frame;
    //    [courseVideoView.playerView addSubview:player.view];
    //    [courseVideoView.playerView sendSubviewToBack:player.view];
    
    __block CourseVideoViewController *blockSelf = self;
    player.failBlock = ^(NSError *error) {
        logdebug(@"error: %@", [error localizedDescription]);
        //TODO:跳出或重置
        //失败的话也得置NO
        //        exchangeVideo = NO;
    };
    
    NSLog(@"videoid=%@--userid=%@--key=%@",player.videoId,player.userId,player.key);
    
    //获取播放的地址
    player.getPlayUrlsBlock = ^(NSDictionary *playUrls) {
        
        logdebug(@"%@",playUrls);
        // [必须]判断 status 的状态，不为"0"说明该视频不可播放，可能正处于转码、审核等状态。
        NSNumber *status = [playUrls objectForKey:@"status"];
        //显示不可播放的原因
        
        self.playUrls = playUrls;
        
        if (status == nil || [status integerValue] != 0) {
            NSString *message = [NSString stringWithFormat:@"%@ %@:%@",
                                 @"videoid",
                                 [playUrls objectForKey:@"status"],
                                 [playUrls objectForKey:@"statusinfo"]];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:message
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        
        [blockSelf setQualityAndPlay];
    };
    
    [player startRequestPlayInfo];
}


- (void)courseOffLineFree:(NSString *)spark{
    
    NSString *localPath;
    localPath = [NSString stringWithFormat:@"%@/%@.%@",DOC_PATH,spark,@"pcm"];
    player.contentURL = [[NSURL alloc]initFileURLWithPath:localPath];
    courseVideoView.menuFull.playBtn.selected = YES;
    courseVideoView.menuMini.playBtn.selected = YES;
    [player prepareToPlay];
    [self playerPlay];
}

- (void)courseOffLine:(NSString *)spark{
    NSString *localPath;
    //    if (player == openPlayer) {
    //        localPath = [NSString stringWithFormat:@"%@/%@.%@",DOC_PATH,spark,@"mp4"];
    //    }else{
    localPath = [NSString stringWithFormat:@"%@/%@.%@",DOC_PATH,spark,@"pcm"];
    //    }
    player.contentURL = [[NSURL alloc]initFileURLWithPath:localPath];
    courseVideoView.menuFull.playBtn.selected = YES;
    courseVideoView.menuMini.playBtn.selected = YES;
    [player prepareToPlay];
    [self playerPlay];
}
#pragma mark - moviePlayerLoadStateDidChange
- (void)moviePlayerLoadStateDidChange
{
    logdebug(@"播放状态改变:%@ playbackState: %ld  %d", player.originalContentURL, (long)player.playbackState,player.drmServerPort);
    //    //状态改变的时候再置NO，否则可能会比较急，容易出问题
    //    exchangeVideo = NO;
    switch (player.loadState) {
        case MPMovieLoadStatePlayable:
            // 可播放
            logdebug(@"%@ playable", player.originalContentURL);
            //            menuview.noteLabel.text = @"正在加载...";
            //            [self.player play];
            //            hideTime = 5;
            break;
            
        case MPMovieLoadStatePlaythroughOK:
            // 状态为缓冲几乎完成，可以连续播放
            logdebug(@"%@ PlaythroughOK", player.originalContentURL);
            //            menuview.noteLabel.text = @"正在加载...";
            //            self.videoStatusLabel.hidden = YES;
            //            hideTime = 5;
            //            [self.player play];
            break;
            
        case MPMovieLoadStateStalled:
            // 缓冲中
            //            logdebug(@"%@ Stalled", self.player.originalContentURL);
            //            menuview.noteLabel.text = @"正在加载...";
            //            hideTime = 5;
            //            [self.player play];
            break;
            
        default:
            break;
    }
    
}
//播放器状态改变
- (void)moviePlayerPlaybackDidFinish:(NSNotification *)notification
{
    logdebug(@"accessLog\n info:%@\n%@", [[NSString alloc]initWithData:player.accessLog.extendedLogData encoding:NSUTF8StringEncoding],[player.accessLog.events firstObject]);
    logdebug(@"errorLog\n info:\n%@", [[NSString alloc]initWithData:player.errorLog.extendedLogData encoding:NSUTF8StringEncoding]);
    NSNumber *n = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
    switch ([n intValue]) {
        case MPMovieFinishReasonPlaybackEnded:
            logdebug(@"PlaybackEnded");
            //播放完成
            break;
            
        case MPMovieFinishReasonPlaybackError:{
            logdebug(@"PlaybackError");
            if (1) {
                //                menuview.noteLabel.text =  @"加载失败";
            }else{
                //                menuview.noteLabel.text =  @"出错，请在线看";
            }
        }
            break;
            
        case MPMovieFinishReasonUserExited:
            logdebug(@"ReasonUserExited");
            break;
            
        default:
            break;
    }
}

#pragma mark - other

//--------------------------------
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
